<template>
 <div class="score-analysis-container">
    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <el-select
        v-model="queryP.semester"
        placeholder="选择学期"
        class="filter-item"
        @change="initCourse"
        clearable
        size="medium"
      >
        <el-option 
          v-for="(semester,index) in availableSemesters" 
          :key="index" 
          :value="semester"
          :label="semester"
        />
      </el-select>
      <el-select
        filterable
        v-model="queryP.subId"
        placeholder="选择课程"
        class="filter-item"
        @change="fetchData"
        clearable
        size="medium"
      >
        <el-option
          v-for="(item, index) in courseList1"
          :key="index"
          :label="item.courseName"
          :value="item.subId"
        />
      </el-select>
    </div>
    <!-- 图表卡片 -->
    <el-card class="chart-card" shadow="hover">
      <div slot="header" class="card-header">
        <i class="el-icon-data-analysis"></i>
        <span>班级成绩对比分析</span>
        <el-tag type="info" size="mini">单位：分</el-tag>
      </div>
      <div class="chart-container">
        <div v-if="scoreData.length === 0" class="no-data">
          <i class="el-icon-picture-outline"></i>
          <span>暂无分析数据</span>
        </div>
        <div v-else ref="chart" class="echarts-box"></div>
      </div>
    </el-card>
  </div>
  </template>
  
  <script>
  import * as echarts from 'echarts'
  import { diffClass,getCourse } from '@/api/student';
  import { getSemester } from '@/api/dashboard';
  export default {
    data(){
        return {
            scoreData:[],
            availableSemesters: [],
            queryP:{},
            courseList1:[]
        }
    },    
    watch: {
      scoreData: {
        
        handler(newVal) {
        // 新增清除图表逻辑
        if (!newVal.length && this.chartInstance) {
          this.chartInstance.dispose()
          this.chartInstance = null
          return
        }
          if (newVal.length) {
            this.$nextTick(() => this.initChart())
          }
        },
        immediate: true
      }
    },
  created(){
    getSemester().then(res=>{
      this.availableSemesters=res.data
    })
  },
    methods: {
        async fetchData(){
            this.scoreData=[]
    try {
        const res = await diffClass(this.queryP)
        this.scoreData = res.data
      } catch (error) {
        this.scoreData = [] // 异常时保持数据清空
        console.error('数据获取失败:', error)
      }
        },
        initCourse(semester){
            getCourse(semester).then(res=>{
                this.courseList1=res.data;
            })
        },
            // 新增重置图表方法
    clearChart() {
      if (this.chartInstance) {
        this.chartInstance.dispose()
        this.chartInstance = null
      }
    },
      initChart() {
        const chartDom = this.$refs.chart
        if (this.chartInstance) {
          this.chartInstance.dispose()
        }
        this.chartInstance = echarts.init(chartDom)
  
        const option = {
          color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C'],
      title: {
        text: '班级成绩对比分析',
        left: 'center',
        textStyle: {
          fontSize: 18,
          color: '#303133'
        }
      },
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(255,255,255,0.98)',
        borderWidth: 0,
        padding: 12,
        extraCssText: 'box-shadow: 0 4px 12px rgba(0,0,0,0.12);',
        formatter: params => {
          return `<div style="font-size:14px;color:#606266">
            <div style="font-weight:600;color:#409EFF;margin-bottom:8px">${params[0].name}</div>
            ${params.map(item => `
              <div style="display:flex;align-items:center;padding:4px 0">
                <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:${item.color};margin-right:8px"></span>
                <span style="flex:1">${item.seriesName}</span>
                <span style="font-weight:500;color:#303133">${item.value[item.encode.y[0]]}分</span>
              </div>
            `).join('')}
          </div>`
        }
      },
      legend: {
        top: 35,
        itemGap: 20,
        textStyle: {
          color: '#606266'
        }
      },
      grid: {
        top: 90,
        bottom: 80,
        containLabel: true
      },
      xAxis: {
        type: 'category',
        axisLabel: {
          rotate: 30,
          fontSize: 12,
          color: '#909399',
          formatter: value => value.length > 6 ? `${value.substr(0,6)}...` : value
        },
        axisLine: {
          lineStyle: {
            color: '#EBEEF5'
          }
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        },
        axisLabel: {
          color: '#909399',
          formatter: '{value} 分'
        }
      },
        dataset: {
          source: this.formatData(),
          dimensions: ['className', 'sumScore', 'dayScore', 'halfScore', 'score']
        },
      series: [
        {
          type: 'bar',
          name: '总成绩',
          barWidth: '20%',
          itemStyle: {
            borderRadius: [4, 4, 0, 0],
            borderWidth: 1,
            borderColor: 'rgba(255,255,255,0.3)'
          }
        },
        {
          type: 'bar',
          name: '平时成绩',
          barWidth: '20%',
          encode: { x: 'className', y: 'dayScore' },
          itemStyle: {  borderRadius: [4, 4, 0, 0],
            borderWidth: 1,
            borderColor: 'rgba(255,255,255,0.3)' }
        },
        {
          type: 'bar',
          name: '期中成绩',
          barWidth: '20%',
          encode: { x: 'className', y: 'halfScore' },
          itemStyle: {  borderRadius: [4, 4, 0, 0],
            borderWidth: 1,
            borderColor: 'rgba(255,255,255,0.3)'}
        },
        {
          type: 'bar',
          name: '期末成绩',
          barWidth: '20%',
          encode: { x: 'className', y: 'score' },
          itemStyle: { borderRadius: [4, 4, 0, 0],
            borderWidth: 1,
            borderColor: 'rgba(255,255,255,0.3)'}
        }
      ],
      dataZoom: [{
        type: 'inside',
        start: 0,
        end: 100,
        fillerColor: 'rgba(64,158,255,0.1)',
        bottom: 30
      }],
      toolbox: {
        right: 20,
        top: 10,
        feature: {
          saveAsImage: {
            title: '保存图片',
            pixelRatio: 2
          },
          magicType: {
            title: { 
              bar: '柱状图', 
              line: '折线图',
              pie: '饼图'
            },
            type: ['bar', 'line', 'pie']
          }
        }
      }
    };
        this.chartInstance.setOption(option)
    },
  
      formatData() {
        // 生成符合 ECharts dataset 要求的数据格式
        const headers = ['className', 'sumScore', 'dayScore', 'halfScore', 'score']
        const data = [headers]
        
        this.scoreData.forEach(item => {
          data.push([
            item.className,
            item.sumScore,
            item.dayScore,
            item.halfScore,
            item.score
          ])
        })
        
        return data
      },
  
      handleResize() {
        if (this.chartInstance) {
          this.chartInstance.resize()
        }
      }
    },
  
    beforeDestroy() {
      window.removeEventListener('resize', this.handleResize)
      if (this.chartInstance) {
        this.chartInstance.dispose()
      }
    }
  }
  </script>
  
<style scoped>
.score-analysis-container {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 48px);
}

/* 筛选区域 */
.filter-section {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}

.filter-item {
  width: 280px;
  transition: all 0.3s;
}

.filter-item:hover ::v-deep .el-input__inner {
  border-color: #409EFF;
}

/* 图表卡片 */
.chart-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 6px 16px rgba(0,0,0,0.08);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 18px 24px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-bottom: 1px solid #ebeef5;
}

.card-header i {
  font-size: 22px;
  color: #409EFF;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 图表容器 */
.chart-container {
  position: relative;
  padding: 20px;
  height: 500px;
  background: #fff;
}

.echarts-box {
  width: 100%;
  height: 560px;
}

.no-data {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #c0c4cc;
}

.no-data i {
  font-size: 56px;
  display: block;
  margin-bottom: 16px;
  opacity: 0.6;
}

.no-data span {
  font-size: 14px;
  letter-spacing: 0.5px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .filter-item {
    width: 100%;
  }
  
  .echarts-box {
    height: 400px;
  }
  
  .card-header {
    padding: 14px;
  }
  
  .card-header i {
    font-size: 18px;
  }
}
</style>